#include <user.h>
#include <io.h>
#include <iobuf.h>
#include <defs.h>
#include <printer.h>
#include <curses.h>
#include <varargs.h>

/**
 * Task that is responsible for all terminal printing.
 */
void Printer() {
  print_req msg;
  int sender_tid;

  int parent_tid;
  Receive(&parent_tid, NULL, 0);
  Reply(parent_tid, NULL, 0);

  RegisterAs("printer");
  
  for ( ; ; ) {
    Receive(&sender_tid, (char*)&msg, sizeof(print_req));
    SaveCursor();
    SetCursorXY(msg.x, msg.y);
    PutStr(msg.str, msg.len);
    LoadCursor();
    /*
    bwprintf(COM2, "\E7");
    bwprintf(COM2, "\E[%d;%dH", msg.y, msg.x);
    PutStr(msg.str, msg.len);
    bwprintf(COM2, "\E8");
    */
    Reply(sender_tid, NULL, 0);
    // Printf("printer\r\n");
  }
}

void PrintAt(int x, int y, char *fmt, ...) {
  int printer_tid = WhoIs("printer");
  char str[IO_BUF_SIZE];
  va_list va;
  va_start(va, fmt);
  int len = STerminalFormat(str, fmt, va);
  // bwprintf(COM1, str);
  // bwprintf(COM1, "\r\n");
  int i;
  va_end(va);
  print_req msg;
  msg.x = x;
  msg.y = y;
  msg.str = str;
  msg.len = len;
  Send(printer_tid, (char*)&msg, sizeof(print_req), NULL, 0);
}
